﻿#include "Config.hpp"

std::map<string,string> Config::CONFIG;

void Config::loadConfig()
{
	  if(CONFIG.size() > 0){
	  	  return;
	  }
	  const int LINE_LENGTH = 255;
		
		//获取当前目录,配置文件 config.txt
		char *file_path_getcwd;
	  file_path_getcwd = new char[LINE_LENGTH];
	  getcwd(file_path_getcwd, LINE_LENGTH);
	  std::string filepath(file_path_getcwd);
	  filepath += "/config.txt";
	  
	  //cout<<filepath<<endl;
	  
	  //从配置文件中获取参数配置
	  char str[LINE_LENGTH];
	  memset(str, '\0', sizeof(str));
	  ifstream fin(filepath.c_str(), ios::in);
	  while(fin.getline(str, LINE_LENGTH)){
	  	 parseConfigLine(str);
	  }
		delete file_path_getcwd;
}

void Config::parseConfigLine(const char* line)
{
	 string ss(line);
	 string key = ss.substr(0, ss.find('='));
	 string value = ss.substr(ss.find('=')+1, ss.length()-1);
	 putConfig(key,value);
}

string Config::getConfigStr(const string key)
{
    map<string,string>::iterator it = CONFIG.find(key);
    if (it != CONFIG.end()){
    	//std::cout << key << ":" << it->second << "\n";
    	return it->second;
    }else{
    	return "";
    }
}

int Config::getConfigInt(const string key)
{
    map<string,string>::iterator it = CONFIG.find(key);
    if (it != CONFIG.end()){
    	//std::cout << key << ":" << it->second << "\n";
    	int b = atoi(it->second.c_str());
    	return b;
    }else{
    	return -1;
    }
}

void Config::putConfig(const string key, const string val)
{
	 CONFIG.insert(pair<string,string>(key,val));
}